﻿namespace uTorrentNAS
{
    using System;
    using System.ComponentModel;
    using System.IO;
    using System.Windows.Forms;
    using System.Windows.Forms.VisualStyles;
    using Services;

    public partial class SettingsForm : Form
    {
        private ConfigurationSource _configurationSource;

        private readonly ConfigurationService _configurationService;
        private readonly TorrentService _torrentService;

        public SettingsForm(ConfigurationService configurationService, TorrentService torrentService)
        {
            _configurationService = configurationService;
            _torrentService = torrentService;

            InitializeComponent();

        }

        private void SettingsForm_Load(object sender, System.EventArgs e)
        {
            var configuration = _configurationService.Retrieve();

            if (configuration == null)
            {
                MessageBox.Show("Settings", "Error while loading settings file (file not found).",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);

                Close();
                return;
            }

            // bind configurations
            _configurationSource = new ConfigurationSource(configuration);

            // uTorrent Settings
            serverAddressTextBox.DataBindings.Add("Text", _configurationSource.GetUTorrentSettings(), "ServerAddress");
            usernameTextBox.DataBindings.Add("Text", _configurationSource.GetUTorrentSettings(), "Username");
            passwordTextBox.DataBindings.Add("Text", _configurationSource.GetUTorrentSettings(), "Password");

            // Scanner Settings
            intervalNumericUpDown.DataBindings.Add("Value", _configurationSource.GetScannerSettings(), "Interval");
            startOnLaunchCheckBox.DataBindings.Add("Checked", _configurationSource.GetScannerSettings(), "StartOnLaunch");

            // Preferences
            extractArchivesCheckBox.DataBindings.Add("Checked", _configurationSource.GetPreferences(), "ExtractArchives");
            cleanupFilesCheckBox.DataBindings.Add("Checked", _configurationSource.GetPreferences(), "CleanupFiles");
            copyFilesCheckBox.DataBindings.Add("Checked", _configurationSource.GetPreferences(), "CopyFiles");
            removeFinishedTorrentCheckBox.DataBindings.Add("Checked", _configurationSource.GetPreferences(), "RemoveFinishedTorrent");

            labelsListBox.DisplayMember = "Name";
            labelsListBox.ValueMember = "Name";
            labelsListBox.DataSource = _configurationSource.GetLabels();

            if (_torrentService.IsStarted())
            {
                serverAddressTextBox.Enabled = false;
                usernameTextBox.Enabled = false;
                passwordTextBox.Enabled = false;

                intervalNumericUpDown.Enabled = false;
            }

        }

        private void btnChooseDestination_Click(object sender, EventArgs e)
        {
            fbdDestination.SelectedPath = destinationPathLabelTextBox.Text;
            if (fbdDestination.ShowDialog(this) == DialogResult.OK)
            {
                destinationPathLabelTextBox.Text = fbdDestination.SelectedPath;
            }
        }

        private void SaveConfiguration()
        {
            _configurationService.Save(_configurationSource.GetConfiguration());
        }

        private void startOnLaunchCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            SaveConfiguration();
        }

        private void intervalNumericUpDown_ValueChanged(object sender, EventArgs e)
        {
            SaveConfiguration();
        }

        private void copyFilesCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            SaveConfiguration();
        }

        private void cleanupFilesCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            SaveConfiguration();
        }

        private void removeFinishedTorrentCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            SaveConfiguration();
        }

        private void extractArchivesCheckBox_CheckedChanged(object sender, EventArgs e)
        {
            SaveConfiguration();
        }

        private void labelsListBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            var selectedName = (string)labelsListBox.SelectedValue;
            if (selectedName != null)
            {
                var labels = _configurationSource.GetLabelItem(selectedName);

                labelNameTextBox.DataBindings.Clear();
                labelNameTextBox.DataBindings.Add("Text", labels, "Name");

                destinationPathLabelTextBox.DataBindings.Clear();
                destinationPathLabelTextBox.DataBindings.Add("Text", labels, "DestinationPath");
            }
        }

        private void addLabelButton_Click(object sender, EventArgs e)
        {
            var list = _configurationSource.GetLabelItem((string)labelsListBox.SelectedValue);
            LabelItem item;
            if (list.Count > 0)
                item = list[0];
            else
                item = new LabelItem()
                {
                    Name = "New Label"
                };
            var i = 1;

            var newName = string.Format("{0}{1}", item.Name, i);
            while (_configurationSource.IsLabelExist(newName))
            {
                newName = string.Format("{0}{1}", item.Name, ++i);
            }

            _configurationSource.AddLabelItem(new LabelItem()
            {
                Name = newName,
                DestinationPath = item.DestinationPath
            });
            if (list.Count > 0)
                labelsListBox.SelectedValue = newName;

            SaveConfiguration();
        }

        private void removeLabelButton_Click(object sender, EventArgs e)
        {
            _configurationSource.DeleteLabelItem((string)labelsListBox.SelectedValue);

            SaveConfiguration();
        }

        private void moveUpLabelButton_Click(object sender, EventArgs e)
        {
            _configurationSource.MoveUpLabelItem((string)labelsListBox.SelectedValue);
        }

        private void moveDownLabelButton_Click(object sender, EventArgs e)
        {
            _configurationSource.MoveDownLabelItem((string)labelsListBox.SelectedValue);
        }

        private void labelNameTextBox_TextChanged(object sender, EventArgs e)
        {
            SaveConfiguration();
        }

        private void destinationPathLabelTextBox_TextChanged(object sender, EventArgs e)
        {
            SaveConfiguration();
        }

        private void labelNameTextBox_Validating(object sender, CancelEventArgs e)
        {
            if (_configurationSource.IsLabelExist(labelNameTextBox.Text))
            {
                e.Cancel = true;
            }
        }
    }
}
